package com.baidu.roomdemo.fragment

import android.os.Bundle
import android.view.View
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.baidu.roomdemo.databinding.FragmentUpdateBinding
import com.baidu.roomdemo.viewmodel.MainViewModel

class UpdateFragment:BaseFragment<FragmentUpdateBinding>() {
    private val mViewModel: MainViewModel by activityViewModels()
    //接收参数
    private val args:UpdateFragmentArgs by navArgs()

    override fun initBinding(): FragmentUpdateBinding {
        return FragmentUpdateBinding.inflate(layoutInflater)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        //显示用户信息
        mBinding.etName.setText(args.user.firstName)
        mBinding.evLastName.setText(args.user.lastName)
        mBinding.evAge.setText(args.user.age.toString())
    }

    override fun initView() {
        mBinding.updateBtn.setOnClickListener {
            val user = args.user
            user.firstName = mBinding.etName.text.toString()
            user.lastName = mBinding.evLastName.text.toString()
            user.age = mBinding.evAge.text.toString().toInt()

            mViewModel.updateUser(user)
            findNavController().popBackStack()
        }

        mBinding.deleteBtn.setOnClickListener {
            mViewModel.deleteUser(args.user)
            findNavController().popBackStack()
        }
    }
}